from django.shortcuts import render
from utils.ResultModel import ResultModel
import os
import json

# Create your views here.

fileDir = './resource/'
fileName = "userInfo.json"
defaultData = {"mid": 0, "name": "", "face": "", "follower": 0}

def getUser(request):
    if not folderIsExists(fileDir):
        os.mkdir(fileDir)
    if not fileIsExists(fileDir + fileName):
        file = open(fileDir + fileName, mode='w', encoding=None)
        file.write(json.dumps(defaultData))
    file = open(fileDir + fileName, mode='r', encoding=None)
    return ResultModel.success(json.loads(file.read()))


def saveUserInfo(request):
    params = request.GET
    keys = ["mid", "name", "face", "follower"]
    for key in keys:
        if not(key in params):
            return ResultModel.error("数据错误")
    file = open(fileDir + fileName, mode='w', encoding=None)
    file.write(json.dumps(params))
    return ResultModel.success()


def logout(request):
    if not folderIsExists(fileDir):
        os.mkdir(fileDir)
    file = open(fileDir + fileName, mode='w', encoding=None)
    file.write(json.dumps(defaultData))
    return ResultModel.success()


def folderIsExists(folder_path):
    return os.path.exists(folder_path)


def fileIsExists(file_path):
    return os.path.exists(file_path)
